package com.ruoyi.fee.service.impl;

import com.ruoyi.fee.domain.PropertyBill;
import com.ruoyi.fee.domain.PropertyFeeType;
import com.ruoyi.fee.mapper.PropertyBillMapper;
import com.ruoyi.fee.mapper.PropertyFeeTypeMapper;
import com.ruoyi.system.domain.PropertyHouse;
import com.ruoyi.system.mapper.PropertyHouseMapper;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Service
public class BillGenerateService {
    @Autowired
    private PropertyBillMapper billMapper;
    @Autowired
    private PropertyHouseMapper houseMapper;
    @Autowired
    private PropertyFeeTypeMapper feeTypeMapper;

    /**
     * 按周期生成账单（每月/每季度/每年）
     */
    public void generateBillsByCycle(String cycle) {
        // 1. 查询所有启用的对应周期的费用类型
        List<PropertyFeeType> feeTypes = feeTypeMapper.selectByCycle(cycle);
        if (CollectionUtils.isEmpty(feeTypes)) {
            return;
        }

        // 2. 计算计费周期（如：本月1日至本月最后一日）
        LocalDate now = LocalDate.now();
        LocalDate startDate = LocalDate.of(now.getYear(), now.getMonth(), 1);
        LocalDate endDate = startDate.plusMonths(1).minusDays(1);
        LocalDate dueDate = endDate.plusDays(15); // 到期日为次月15日

        // 3. 遍历所有房屋生成账单
        List<PropertyHouse> houses = houseMapper.selectAllInhabited(); // 只对已入住房屋生成账单
        for (PropertyHouse house : houses) {
            for (PropertyFeeType feeType : feeTypes) {
                // 计算金额（按面积计费：面积 × 单价）
                BigDecimal amount = calculateAmount(house, feeType);
                if (amount.compareTo(BigDecimal.ZERO) <= 0) {
                    continue;
                }

                // 生成账单
                PropertyBill bill = new PropertyBill();
                bill.setBillNo(generateBillNo());
                bill.setHouseId(house.getHouseId());
                bill.setTypeId(feeType.getTypeId());
                bill.setAmount(amount);
                bill.setStartDate(startDate);
                bill.setEndDate(endDate);
                bill.setDueDate(dueDate);
                bill.setStatus("UNPAID");
                billMapper.insertPropertyBill(bill);
            }
        }
    }

    // 计算费用金额
    private BigDecimal calculateAmount(PropertyHouse house, PropertyFeeType feeType) {
        if ("AREA".equals(feeType.getChargeRule())) {
            // 按面积计费：面积 × 单价
            return house.getArea().multiply(feeType.getUnitPrice());
        } else if ("FIXED".equals(feeType.getChargeRule())) {
            // 固定金额
            return feeType.getUnitPrice();
        }
        return BigDecimal.ZERO;
    }

    // 生成唯一账单编号（规则：W + 年月日 + 6位随机数）
    private String generateBillNo() {
        return "W" + LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"))
               + RandomUtils.nextInt(100000, 999999);
    }
}